<?php
declare(strict_types=1);

namespace App\Services;

use App\Component\RedisUserSever;
use App\Constants\Security;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Codec\Json;

class loginServices
{
    public static $key = "root:123456789as";

    public static function login($auth, $pass)
    {
        $auth = trim($auth);
        $pass = trim($pass);
        $user = Db::table("web_user")->where("auth", $auth)->first();

        if (!$user) {
            return ["status" => false, "msg" => "用户名或密码错误"];
        }

        $oldPass = Security::decrypt($user->password, static::$key);
        if ($oldPass != $pass || empty($oldPass)) {
            return ["status" => false, "msg" => "用户名或者密码错误"];
        }

        $user = [
            "id"        => $user->id,
            "auth"      => $user->auth,
            "name"      => $user->name,
            "img"       => $user->img,
            "email"     => $user->email,
            "update_at" => $user->update_at
        ];

        $token = static::setToken($user, true);
        return ["status" => true, "msg" => "", "token" => $token, "data" => $user];
    }

    public static function setToken($user, $dan)
    {
        $token = Security::encrypt(time().":".$user["id"].":".$user["auth"], static::$key);
        $token = urlencode($token);
        $user["token"] = $token;
        $redisUser = new RedisUserSever();

        if ($dan) {
            $oldUser = $redisUser->getUserInfo($user["id"]);
            if ($oldUser) {
                $oldUser = json::decode($oldUser);
                $key = $oldUser["token"] ?? "";
                $redisUser->delUserInfo($key);
            }
        }

        $redisUser->setUserToken($user, 4 * 60 * 60);
        return $token;
    }

    public static function getUserInfo($token)
    {
        $redisUser = new RedisUserSever();
        $userId = $redisUser->getUserByToken($token);

        $user = $redisUser->getUserInfo($userId);
        if ($user) {
            $user = json::decode($user);
        } else {
            $user = null;
        }
        return $user;
    }
}
